package com.gxa.meiye.sso.controller;

import com.gxa.meiye.core.common.JsonResult;
import com.gxa.meiye.core.exception.BusinessException;
import com.gxa.meiye.core.exception.ExceptionCode;
import com.gxa.meiye.sso.entity.Consumer;
import com.gxa.meiye.sso.service.ConsumerService;
import com.gxa.meiye.sso.service.LogService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import java.util.Map;

/**
 * @Author: zy
 * @CreateTime: 2022-07-19  21:22
 */
@RestController
@Api(value = "登录",tags = "登录接口")
@RequestMapping("/consumer")
@Validated
public class LogController {
    @Autowired
    private ConsumerService userService;
    @Autowired
    private LogService logService;
    @GetMapping("/login")
    public Map login(
            @RequestParam("phone")
            @NotEmpty(message = "手机号不为空") String phone,
            @RequestParam("code")
            @NotEmpty(message = "验证码不为空")String code) throws Exception {
//        if(!phone.matches("^[1](([3][0-9])|([4][5,7,9])|([5][0-9])|([6][6])|([7][3,5,6,7,8])|([8][0-9])|([9][8,9]))[0-9]{8}$")){
//        throw new BusinessException(ExceptionCode.WRONG_PHONE);
//    }
        //String token = userService.login(phone, code);
        //System.out.println(token);
        String token = userService.login(phone, code);
        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("登录成功");
        jsonResult.setData(phone);
        jsonResult.put(token);
        //jsonResult.put(token);
        // {code:1,token:{id:,name:}}
        return jsonResult.getMap();
    }
    @PostMapping("/check")
    public Map check(String token) throws Exception {
        System.out.println(token);
        Consumer consumer = userService.checkToken(token);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setData(consumer);
        return jsonResult.getMap();
    }
    //退出接口
    @PostMapping("/logout")
    public Map log(String phone){
        boolean del = logService.del(phone);
        JsonResult jsonResult=new JsonResult();
        if (del) {
            jsonResult.setCode("1");
            jsonResult.setMsg("退出成功");
            return jsonResult.getMap();
        }else {
            jsonResult.setCode("0");
            jsonResult.setMsg("退出失败");
            return jsonResult.getMap();
        }
    }

}

